'''
Created on Sep 18, 2010

@author: oabalbin
'''
import os
import glob
import numpy as np
from optparse import OptionParser
from collections import deque, defaultdict

def process_file(fastafile, outfasta, mirna_len=24):
    outfile = open(outfasta,'w')
    flag=False
    collapse_sequences = defaultdict(int)
    #cth = 1e3
    #c=0
    for line in fastafile:
        if line.startswith('>') and not flag:
            header=line.strip('\n')
            #outfile.write(line)
            flag=True
            continue
        
        if flag:
            collapse_sequences = read_extractor_write2(list(line.strip('\n')),outfile,header, mirna_len,collapse_sequences)
            flag=False
            #c+=1
    
    seqcount=0
    for readseq, mycount in collapse_sequences.iteritems():
        outfile.write('>hsa_'+str(seqcount)+'_x'+str(mycount)+'\n')
        outfile.write(readseq+'\n')
        seqcount += mycount

    outfile.close()

def read_extractor_write(read, outfile,header, mirna_len):
            
    #mirna_len=24
    read_length=len(read)
    i,j=0,0
    
    while (j < read_length):        
        j= i+mirna_len
        outfile.write(header+'_'+str(i)+'\n')
        outfile.write(",".join(read[i:j]).replace(',','')+'\n')
        i+=1

def read_extractor_write2(read, outfile,header, mirna_len, sequences_dict):
            
    #mirna_len=24
    read_length=len(read)
    i,j=0,0
    
    while (j < read_length):        
        j= i+mirna_len
        #outfile.write(header+'_'+str(i)+'\n')
        readseq = ",".join(read[i:j]).replace(',','')
        #outfile.write(readseq+'\n')
        i+=1
        sequences_dict[readseq]+=1
    
    return sequences_dict
        

        
def read_extractor(read, mirna_len):
            
    read_collect=deque()
    
    read_length=len(read)
    for i in range(read_length):
        j=read_length - i+mirna_len
        read_collect.append(read[i:j])
            
    return read_collect

def read_files_folder(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=defaultdict()
    
    for infile in glob.glob( os.path.join(folderpath, '*'+ext) ):
        filename=infile.split('/')[-1]
        myfiles[filename]=infile
        #print "current file is: " + filename
    return myfiles


if __name__ == '__main__':
    
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-t", "--reads", dest="reads",
                            help="Fasta file with the original reads")
    optionparser.add_option("-o", "--chopped", dest="chopped",
                            help="bed file with transcripts-exons of interest")
    optionparser.add_option("-l", "--mirnalen", dest="mirnalen",
                            help="length of mers that you want to extract from each read. It should be smaller than any read")

    
    (options, args) = optionparser.parse_args()

    
    
        
    inputfile_name=options.reads
    outputfile_name=options.chopped
    mirna_len= int(options.mirnalen)
    
    inputfile = open(inputfile_name)
    process_file(inputfile, outputfile_name,mirna_len)
    

    
    